package com.raising.framework.shiro;

import com.raising.framework.config.JConfig;
import com.raising.framework.entity.ResultCode;
import com.raising.framework.entity.ResultVo;
import com.raising.utils.EncodesUtils;
import com.raising.utils.JStringUtils;
import com.raising.utils.RequestUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 判断登录用户的 session 有没有超时失效
 */
public class MyAccessFilter extends AccessControlFilter {

    private static final Logger logger = LoggerFactory.getLogger(MyAccessFilter.class);

    /**
     * 判断session是否失效
     * @author GaoYuan
     * @datetime 2017/12/15 上午9:29
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
//        if(logger.isDebugEnabled()){
//            logger.debug("【Shiro】>>> MyAccessFilter.isAccessAllowed()，判断session是否失效");
//        }
//        Session session = getSubject(request, response).getSession(false);
//        if(session == null) {
//            // 说明session失效
//            return false;
//        }
//        if(session.getAttribute(JConfig.SESSION_FORCE_LOGOUT_KEY) != null){
//            // 不等于null，表示被强制退出。
//            return false;
//        }
//        return true;

        Session session = getSubject(request, response).getSession(false);
        if(session == null) {
            return true;
        }
        return session.getAttribute(JConfig.SESSION_FORCE_LOGOUT_KEY) == null;
    }

    /**
     * session失效再跳转后，会进入此方法
     * isAccessAllowed = false 进入
     * @author GaoYuan
     * @datetime 2017/12/15 上午9:28
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if(logger.isDebugEnabled()){
            logger.debug("【Shiro】>>> MyAccessFilter.onAccessDenied()，session超时失效");
        }
        try {
            //强制退出
            Subject subject = getSubject(request, response);
            if(subject != null){
                subject.logout();
            }
        } catch (Exception e) {

        }
        HttpServletRequest re = (HttpServletRequest)request;

        if(RequestUtils.isAjax(re)){
            // 如果是ajax请求
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            RequestUtils.ajaxResponse(httpServletResponse, ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("Session失效"));
        }else{
            // 表单请求
            String oldUrl = EncodesUtils.urlEncode(re.getRequestURL() + "?" + re.getQueryString());
            String loginUrl = getLoginUrl() + (getLoginUrl().contains("?") ? "&" : "?") + "forceLogout=1";
            if(JStringUtils.isNotBlank(oldUrl)){
                loginUrl = loginUrl + "&jumpUrl="+oldUrl;
            }
            WebUtils.issueRedirect(request, response, loginUrl);
        }
        // 阻止往下的链路
        return false;
    }
}
